//
//  ClockSettingViewController.m
//  拖小延闹钟
//
//  Created by rimi on 15/10/12.
//  Copyright (c) 2015年 Liukai. All rights reserved.
//

#import "ClockSettingViewController.h"
#define VIEW_WIDTH CGRectGetWidth(self.view.bounds) - 40

@interface ClockSettingViewController ()
enum {
    ButtonTag = 100
};
@property (nonatomic, strong) UIView *datePickerView;//装载所有子视图的view
@property (nonatomic, strong) UIButton *cancelButton;//取消按钮
@property (nonatomic, strong) UIButton *sureButton;   //储存按钮
@property (nonatomic, strong) UILabel *contentLabel;  //标签详细信息
@property (nonatomic, strong) UILabel *soundContent;   //铃声详细信息
@end

@implementation ClockSettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor cyanColor];
    [self initInterface];
}

- (void)initInterface {
    [self.view addSubview:self.datePickerView];
    [self.datePickerView addSubview:self.cancelButton];
    [self.datePickerView addSubview:self.sureButton];
    [self.datePickerView addSubview:self.datePicker];
    [self startLayout];    //开始布局.
}

- (void)startLayout {
    //重复图层
    UIView *repeatView= [[UIView alloc] initWithFrame:CGRectMake(20, CGRectGetHeight(self.view.bounds) / 2 - 33, VIEW_WIDTH, CGRectGetHeight(self.view.bounds) / 10)];
    repeatView.layer.cornerRadius = 20;
    repeatView.clipsToBounds = YES;
    repeatView.backgroundColor = [UIColor whiteColor];
    [self.datePickerView addSubview:repeatView];
                            //重复按钮
    UILabel *repTip = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetWidth(self.view.bounds) / 2 - 60, 0, 80, 30)];
    repTip.text = @"请选择重复";
    repTip.font = [UIFont systemFontOfSize:16];
    repTip.textColor = [UIColor blackColor];
    [repeatView addSubview:repTip];
    NSArray *itemArray = @[@"周一",@"周二",@"周三",@"周四",@"周五",@"周六",@"周日"];
//    LKSinggleSelectionControl *lkView = [[LKSinggleSelectionControl alloc] initWithFrame:CGRectMake(20, 30, VIEW_WIDTH, CGRectGetHeight(self.view.bounds) / 7 - 30) items:itemArray];
    CGFloat buttonWidth = 50;
    CGFloat interval = - 5;
   
    [itemArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
         UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:obj forState:UIControlStateNormal];
    button.frame = CGRectMake(idx * (buttonWidth + interval) + 15, 30, 30, 20);
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:12];
    [button setTitleColor:[UIColor orangeColor] forState:UIControlStateSelected];
    [button addTarget:self action:@selector(handleEvent:) forControlEvents:UIControlEventTouchUpInside];
    button.tag = ButtonTag + idx;
    [repeatView addSubview:button];
    }];
    NSString *repeatStr = self.settingDataSource[self.index][@"repeat"];
    NSArray *repeatArray = [repeatStr componentsSeparatedByString:@","];
    for (int i = 0; i < repeatArray.count; i ++) {
        if ([repeatArray[i] isEqualToString:@"周一"]) {
            UIButton *button = (UIButton *)[self.view viewWithTag:100];
                    button.selected = YES;
        }
        if ([repeatArray[i] isEqualToString:@"周二"]) {
            UIButton *button = (UIButton *)[self.view viewWithTag:101];
            button.selected = YES;
        }
        if ([repeatArray[i] isEqualToString:@"周三"]) {
            UIButton *button = (UIButton *)[self.view viewWithTag:102];
            button.selected = YES;
        }
        if ([repeatArray[i] isEqualToString:@"周四"]) {
            UIButton *button = (UIButton *)[self.view viewWithTag:103];
            button.selected = YES;
        }
        if ([repeatArray[i] isEqualToString:@"周五"]) {
            UIButton *button = (UIButton *)[self.view viewWithTag:104];
            button.selected = YES;
        }
        if ([repeatArray[i] isEqualToString:@"周六"]) {
            UIButton *button = (UIButton *)[self.view viewWithTag:105];
            button.selected = YES;
        }
        if ([repeatArray[i] isEqualToString:@"周日"]) {
            UIButton *button = (UIButton *)[self.view viewWithTag:106];
            button.selected = YES;
        }
    }
    //铃声图层
    UIView *soundView = [[UIView alloc] initWithFrame:CGRectMake(20, 2 *CGRectGetHeight(self.view.bounds) / 3 - 55, VIEW_WIDTH, CGRectGetHeight(self.view.bounds) / 10)];
    soundView.layer.cornerRadius = 15;
    soundView.clipsToBounds = YES;
    soundView.backgroundColor = [UIColor whiteColor];
    [self.datePickerView addSubview:soundView];
    UIButton *tipButton = [UIButton buttonWithType:UIButtonTypeCustom];
    tipButton.frame = CGRectMake(CGRectGetWidth(self.view.bounds) - 80, 20, 30, 30);
    [tipButton setBackgroundImage:[UIImage imageNamed:@"前进"] forState:UIControlStateNormal];
    [soundView addSubview:tipButton];
    UILabel *soundLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 20, 80, 30)];
    soundLabel.text = @"铃声:";
    soundLabel.font = [UIFont systemFontOfSize:15];
    [soundView addSubview:soundLabel];
    UILabel *soundContent = [[UILabel alloc] initWithFrame:CGRectMake(100, 20, CGRectGetWidth(self.view.bounds) - 50, 30)];
    soundContent.font = [UIFont systemFontOfSize:15];
    soundContent.text = @"懒虫起床";
    [soundView addSubview:soundContent];
    UITapGestureRecognizer *soundTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(setSound:)];
    [soundView addGestureRecognizer:soundTap];
    
    //标签图层
    UIView *labelView = [[UIView alloc] initWithFrame:CGRectMake(20, 2 *CGRectGetHeight(self.view.bounds) / 3 + 33, VIEW_WIDTH, CGRectGetHeight(self.view.bounds) / 10)];
    labelView.layer.cornerRadius = 20;
    labelView.clipsToBounds = YES;
    labelView.userInteractionEnabled = YES;
    labelView.backgroundColor = [UIColor whiteColor];
    [self.datePickerView addSubview:labelView];
    UIButton *tipButton2 = [UIButton buttonWithType:UIButtonTypeCustom];
    tipButton2.frame = CGRectMake(CGRectGetWidth(self.view.bounds) - 80, 20, 30, 30);
    [tipButton2 setBackgroundImage:[UIImage imageNamed:@"前进"] forState:UIControlStateNormal];
    [labelView addSubview:tipButton2];
                //标签
    UILabel *messageTip = [[UILabel alloc] initWithFrame:CGRectMake(10, 20, 80, 30)];
    messageTip.text = @"标签信息:";
    messageTip.font = [UIFont systemFontOfSize:15];
    [labelView addSubview:messageTip];
    UILabel *contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 20, CGRectGetWidth(self.view.bounds) - 50, 30)];
    contentLabel.font = [UIFont systemFontOfSize:15];
    contentLabel.text = @"起来嗨！";
    [labelView addSubview:contentLabel];
    self.contentLabel = contentLabel;
    self.contentLabel.text = self.settingDataSource[self.index][@"label"];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(inputLabelMessage:)];
    [labelView addGestureRecognizer:tap];
    //删除按钮
    UIButton *deleteButton = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetWidth(self.view.bounds) / 5, CGRectGetHeight(self.view.bounds) - 100, CGRectGetWidth(self.view.bounds) * 3 / 5, 60)];
    [deleteButton setTitle:@"删除闹钟" forState:UIControlStateNormal];
    deleteButton.backgroundColor = [UIColor redColor];
    deleteButton.layer.cornerRadius = 10;
    deleteButton.clipsToBounds = YES;
    [deleteButton addTarget:self action:@selector(deleteTheClock:) forControlEvents:UIControlEventTouchUpInside];
    [self.datePickerView addSubview:deleteButton];

}

#pragma mark -- Getter
- (UIView *)datePickerView {
    if (!_datePickerView) {
        _datePickerView = ({
            UIView *pickerView = [[UIView alloc] initWithFrame:self.view.bounds];
            pickerView.backgroundColor = [UIColor grayColor];
            pickerView.alpha = 0.9;
            pickerView;
        });
    }
    return _datePickerView;
}

- (UIDatePicker *)datePicker {
    if (!_datePicker) {
        _datePicker = ({
            UIDatePicker *datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 64, 0,0)];
            NSString *timeStr = self.settingDataSource[_index][@"time"];
            NSDateFormatter *dateformartter = [[NSDateFormatter alloc] init];
            [dateformartter setDateFormat:@"HH:mm"];
            NSDate *clockTime = [dateformartter dateFromString:timeStr];
            [datePicker setDate:clockTime];
            [datePicker setDatePickerMode:UIDatePickerModeTime];
            datePicker.backgroundColor = [UIColor whiteColor];
            datePicker.layer.cornerRadius = 80;
            datePicker.clipsToBounds = YES;
            datePicker;
        });
    }
    return _datePicker;
}

- (UIButton *)cancelButton {
    CGFloat buttonWidth = CGRectGetWidth(self.view.bounds) / 5;
    if (!_cancelButton) {
        self.cancelButton = ({
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = CGRectMake(10, 15, buttonWidth,50);
            [button setTitle:@"取消" forState:UIControlStateNormal];
            [button addTarget:self action:@selector(action_cancelEvent:) forControlEvents:UIControlEventTouchUpInside];
            button;
        });
    }
    return _cancelButton;
}

- (UIButton *)sureButton {
    CGFloat buttonWidth = CGRectGetWidth(self.view.bounds) / 5;
    if (!_sureButton) {
        self.sureButton = ({
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = CGRectMake(CGRectGetWidth(self.view.bounds) - 10 - buttonWidth, 15, buttonWidth,50);
            [button setTitle:@"存储" forState:UIControlStateNormal];
            [button addTarget:self action:@selector(action_sureEvent:) forControlEvents:UIControlEventTouchUpInside];
            button;
        });
    }
    return _sureButton;
}

//删除闹钟
- (void)deleteTheClock:(UIButton *)sender {
    [self.settingDataSource removeObjectAtIndex:self.index];
    [[NSUserDefaults standardUserDefaults] setObject:self.settingDataSource forKey:@"datasource"];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"deleteClock" object:nil];
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark -- private method
- (void)handleEvent:(UIButton *)sender {

    sender.selected = !sender.selected;
}
//确定取消
- (void)action_cancelEvent:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)action_sureEvent:(UIButton *)sender {
    NSMutableArray *repeatArray = [NSMutableArray arrayWithCapacity:7];    //用来存储重复的选择
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"mon"] isEqual:@"YES"]) {
        [repeatArray addObject:@"周一"];
    }
    if([[[NSUserDefaults standardUserDefaults] objectForKey:@"tues"] isEqual:@"YES"]) {
        [repeatArray addObject:@"周二"];
    }
    if([[[NSUserDefaults standardUserDefaults] objectForKey:@"wednes"] isEqual:@"YES"]) {
        [repeatArray addObject:@"周三"];
    }
    if([[[NSUserDefaults standardUserDefaults] objectForKey:@"thurs"] isEqual:@"YES"]) {
        [repeatArray addObject:@"周四"];
    }
    if([[[NSUserDefaults standardUserDefaults] objectForKey:@"fri"] isEqual:@"YES"]) {
        [repeatArray addObject:@"周五"];
    }
    if([[[NSUserDefaults standardUserDefaults] objectForKey:@"satur"] isEqual:@"YES"]) {
        [repeatArray addObject:@"周六"];
    }
    if([[[NSUserDefaults standardUserDefaults] objectForKey:@"sun"] isEqual:@"YES"]) {
        [repeatArray addObject:@"周日"];
    }
    //没选中
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"mon"] isEqual:@"NO"]) {
        [repeatArray removeObject:@"周一"];
    }
    if([[[NSUserDefaults standardUserDefaults] objectForKey:@"tues"] isEqual:@"NO"]) {
        [repeatArray removeObject:@"周二"];
    }
    if([[[NSUserDefaults standardUserDefaults] objectForKey:@"wednes"] isEqual:@"NO"]) {
        [repeatArray removeObject:@"周三"];
    }
    if([[[NSUserDefaults standardUserDefaults] objectForKey:@"thurs"] isEqual:@"NO"]) {
        [repeatArray removeObject:@"周四"];
    }
    if([[[NSUserDefaults standardUserDefaults] objectForKey:@"fri"] isEqual:@"NO"]) {
        [repeatArray removeObject:@"周五"];
    }
    if([[[NSUserDefaults standardUserDefaults] objectForKey:@"satur"] isEqual:@"NO"]) {
        [repeatArray removeObject:@"周六"];
    }
    if([[[NSUserDefaults standardUserDefaults] objectForKey:@"sun"] isEqual:@"NO"]) {
        [repeatArray removeObject:@"周日"];
    }
    NSString *str = [repeatArray componentsJoinedByString:@","];
    //时间传值
    NSDate *date = [_datePicker date];
    NSDateFormatter *forMartter = [[NSDateFormatter alloc] init];
    [forMartter setDateFormat:@"HH:mm"];
    NSString *backStr = [forMartter stringFromDate:date];
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:self.contentLabel.text,@"label",str,@"repeat",backStr,@"time",nil];
    [self.settingDataSource addObject:dic];
//        self.settingDataSource = [[NSUserDefaults standardUserDefaults] objectForKey:@"datasource"];

    if (self.cellContent) {
        self.cellContent(self.settingDataSource);
        [[NSUserDefaults standardUserDefaults] setObject:self.settingDataSource forKey:@"datasource"];
        //发送通知
        NSString *clockNumber = [NSString stringWithFormat:@"%ld",(long)self.index];
        NSDictionary *userInfo = [NSDictionary dictionaryWithObject:clockNumber forKey:@"idx"];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"changeSetting" object:nil userInfo:userInfo];
    }
    [self.navigationController popViewControllerAnimated:YES];
}
//编辑标签信息
- (void)inputLabelMessage:(UITapGestureRecognizer *)gesture {
    LabelDetailViewController *detailVC = [[LabelDetailViewController alloc] init];
    [self.navigationController pushViewController:detailVC animated:YES];
    [detailVC sendMessage:^(NSString *message) {
        self.contentLabel.text = message;
    }];
}

- (void)setSound:(UITapGestureRecognizer *)gesture {
    SoundSelectedViewController *soundVC = [[SoundSelectedViewController alloc] init];
    [self.navigationController pushViewController:soundVC animated:YES];
}
- (void)getTheCellContent:(BlockContent)block {
    self.cellContent = block;
}
@end
